package com.senior.threadlocal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

public class ThreadLocalDateUtils {

    //使用全局的，多线程范围会出错
    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-HH-dd HH:mm:ss");

    //所以我们用ThreadLocal来做，让每个变量人手一份
    public static final ThreadLocal<SimpleDateFormat> sdf =
            ThreadLocal.withInitial(()->new SimpleDateFormat("yyyy-HH-dd HH:mm:ss"));


    public static void main(String[] args) throws ParseException {
        //System.out.println(ThreadLocalDateUtils.Parse("2021-11-11 11:12:23"));
        for (int i = 0; i <10 ; i++) {
            new Thread(()->{
                try {
                    System.out.println(ThreadLocalDateUtils.Parse("2021-11-11 11:12:23"));
                } catch (ParseException e) {
                    e.printStackTrace();
                }finally {
                    sdf.remove();
                }
            },"T1").start();
        }
    }
    //这边可以通过加锁来解决，但是比较慢
    public static  Date Parse(String stringDate) throws ParseException {
        return sdf.get().parse(stringDate);
    }

}
